package com.service;

import cn.hutool.core.util.RandomUtil;
import com.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class MailServiceImpl implements IMailService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String form;


    public void sendMail(String mail){


        String code= RandomUtil.randomString(4);
        redisTemplate.boundZSetOps("mail").add(mail+":"+code,System.currentTimeMillis());

        //发送
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(form);
        message.setTo(mail);
        message.setSubject("验证码注册");
        message.setText("你的验证码："+code);
        javaMailSender.send(message);

    }

    public boolean checkCode(String mail,String code){
        //从redis 取出验证码
        BoundZSetOperations zset=redisTemplate.boundZSetOps("mail");
        Long mingci=redisTemplate.boundZSetOps("mail").rank(mail+":"+code);
        boolean f=mingci!=null;
        if (f){
            zset.removeRange(mingci,mingci);
        }
        return f;
    }


}
